package Arrays;

/**
 * 作者:hfj
 * 功能:28.找出字符串中第一个匹配项的下标
 * 日期: 2025/10/17 21:37
 */
public class StrStr {
    public static void main(String[] args) {
        String haystack = "sadbutsad";
        String needle = "sad";
        System.out.println(strStr(haystack,needle));
    }

    //暴力解,还可以使用KMP算法实现
    public static int strStr(String haystack, String needle) {
        int left = 0, right = needle.length() - 1;
        //子串与目标子串进行匹配
        while (right <= haystack.length() - 1) {
            //截取字符串
            if (haystack.substring(left, right + 1).equals(needle)){
                return left;
            }
            left++;
            right++;
        }
        return -1;//没找到返回-1
    }
}
